package com.rongshu.sendmessage.util.upData;

import android.content.Context;
import android.os.Build;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.rongshu.sendmessage.R;
import com.rongshu.sendmessage.view.banner.GlideRoundTransform;

import java.util.List;

public class ImagesAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> implements View.OnClickListener {


    private List<String> images;
    private Context context;

    public ImagesAdapter(List<String> images, Context context) {
        this.images = images;
        this.context = context;
    }

    private OnItemClickListener mOnItemClickListener = null;


    //define interface
    public static interface OnItemClickListener {
        void onItemClick(View view, int position);
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
        View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.images_recyclerview, viewGroup, false);
        TopViewHolder vh = new TopViewHolder(view);
        view.setOnClickListener(this);

        return vh;
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        holder.itemView.setTag(position);

        final TopViewHolder topViewHolder = (TopViewHolder) holder;
        if (images.get(position) != null && !images.get(position).equals("")) {
            Glide.with(context)
                    .load(images.get(position))
                    .transform(new CenterCrop(context), new GlideRoundTransform(context))
                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                    .dontAnimate()
                    .crossFade()
                    .into(topViewHolder.bgImg);
        }
    }


    @Override
    public void onClick(View v) {
        if (mOnItemClickListener != null) {
            //注意这里使用getTag方法获取position
            mOnItemClickListener.onItemClick(v, (int) v.getTag());
        }
    }

    public void setOnItemClickListener(OnItemClickListener listener) {
        this.mOnItemClickListener = listener;
    }


    //获取数据的数量
    @Override
    public int getItemCount() {
        return images.size();
    }


    //自定义的ViewHolder，持有每个Item的的所有界面元素
    public static class TopViewHolder extends RecyclerView.ViewHolder {
        ImageView bgImg;
        public TopViewHolder(View view) {
            super(view);
            bgImg=view.findViewById(R.id.iv_bg);
        }
    }
}
